package com.tenglong.teacher.ui.homepage;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.clean.DataCleanManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.PublishHomeworkResurtInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.audio.AudioRecorderButton;
import com.tenglong.teacher.ui.audio.MediaManager;
import com.tenglong.teacher.ui.audio.Recorder;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.dialog.ExitDialog;
import com.tenglong.teacher.ui.utils.MyUtils;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PublishHomeworkActivity extends BaseActivity implements GridImageAdapter.OnItemClickListener, AudioRecorderButton.AudioFinishRecorderListener {

    public static final String KEY_IS_REISSUE = "key_is_reissue";
    private EditText et_content;
    private AudioRecorderButton mAudioRecorderButton;

    private String classID;

    private RecyclerView recyclerView;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private final int maxSelectNum = 8;
    private TextView mAudio;//btn_audio
    private Button mDeleteAudio;//btn_delete_auto
    private Recorder mRecorder;
    private RelativeLayout mRelaAudio;//rl_audio
    private boolean isReissue;
    private List<String> classIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_homework);
        Intent intent = getIntent();
        isReissue = intent.getBooleanExtra(KEY_IS_REISSUE, false);
        if(intent.hasExtra(MyUtils.CLASSID)){
            classID = intent.getStringExtra(MyUtils.CLASSID);
        }
        if(intent.hasExtra(MyUtils.CLASSIDLIST)){
            classIds=intent.getStringArrayListExtra(MyUtils.CLASSIDLIST);
        }
        initView();
        initRecy();
        setListeners();
        getAudioPermission();
    }

    private void initRecy() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(PublishHomeworkActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(PublishHomeworkActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recyclerView.setAdapter(adapter);
    }

    private void setListeners() {
        mAudio.setOnClickListener(this);
        mDeleteAudio.setOnClickListener(this);
        adapter.setOnItemClickListener(this);
        mAudioRecorderButton.setAudioFinishRecorderListener(this);
    }

    private void initView() {
        setTitle("发布作业");
        mRight.setText("发送");
        mRight.setVisibility(View.VISIBLE);
        mRight.setOnClickListener(this);
        mRight.setBackground(null);
        et_content = findViewById(R.id.et_content);
        mAudioRecorderButton = findViewById(R.id.id_recorder_button);
        mAudio = findViewById(R.id.btn_audio);
        mDeleteAudio = findViewById(R.id.btn_delete_auto);
        mRelaAudio = findViewById(R.id.rl_audio);
        recyclerView = findViewById(R.id.recycler);
    }


    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(PublishHomeworkActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .setOutputCameraPath(getPath())// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示 true or false
                    .isGif(false)// 是否显示gif图片 true or false
                    .compressSavePath(getPath())//压缩图片保存地址
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.right_btn:
                if (et_content.getText().toString().trim().length() == 0 &&
                        mRecorder == null &&
                        selectList.size() == 0) {
                    ToastUtils.showCenterToast("请输入作业内容后再发送作业");
                    return;
                } else {
                    handleImage();
                }
                break;
            case R.id.btn_delete_auto:
                mRelaAudio.setVisibility(View.GONE);
                mRecorder = null;
                break;
            case R.id.btn_audio:
                if (mRecorder != null) {
                    MediaManager.release();
                    MediaManager.playSound(mRecorder.getFilePath(), null);
                }
                break;
        }

    }

    private void handleImage() {
        showProgressDialog("作业发布中...");
        if (selectList.size() == 0) {
             publishwork(null);
            return;
        }
        String[] files = new String[selectList.size()];
        for (int i = 0; i < selectList.size(); i++) {
            files[i] = selectList.get(i).getPath();
        }
        final Tiny.FileCompressOptions compressOptions = new Tiny.FileCompressOptions();
        compressOptions.config = Bitmap.Config.RGB_565;
        compressOptions.isKeepSampling = true;
        compressOptions.compressDirectory = DataCleanManager.getPublishHomeworkLink(this);
        Tiny.getInstance().source(files).batchAsFile().withOptions(compressOptions).batchCompress(new FileBatchCallback() {
            @Override
            public void callback(boolean isSuccess, String[] outfiles, Throwable t) {
                if (!isSuccess) {
                    ToastUtils.showCenterToast("图片预处理失败");
                    return;
                }
                publishwork(outfiles);
            }
        });
    }

    private void publishwork(String[] outfiles) {
        Map<String, RequestBody> photos = new HashMap<>();
        if (outfiles != null) {
            for (int i = 0; i < outfiles.length; i++) {
                photos.put("files\"; filename=\"" + i + ".png", RequestBody.create(MediaType.parse("multipart/form-data"),
                        new File(outfiles[i])));
            }
        }
        if (mRecorder != null) {
            photos.put("files\"; filename=\"" + selectList.size() + ".amr", RequestBody.create(MediaType.parse("multipart/form-data"),
                    new File(mRecorder.getFilePath())));
        }
        if (photos.size() == 0) {
            photos.put("files\"; filename=\"" + selectList.size() + ".png", RequestBody.create(null, ""));
        }
        Call<BaseResult<PublishHomeworkResurtInfo>> service;
        if (!isReissue) {
            service = CreateRequestEntity.getWebService().publishFromWeb(DataState.getInstance().getUserInfo().getId(), et_content.getText().toString().trim(), classID, photos);
        } else {
            service = CreateRequestEntity.getWebService().publishHomeworkFromClasss(DataState.getInstance().getUserInfo().getId(), et_content.getText().toString().trim(), classIds, photos);
        }
        service.enqueue(new Callback<BaseResult<PublishHomeworkResurtInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<PublishHomeworkResurtInfo>> call, Response<BaseResult<PublishHomeworkResurtInfo>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    Intent intent = new Intent();
                    intent.putExtra(GlobalConstant.RESULT_CODE_PUBLISH_HOMEWORK_ID, response.body().data.homeworkId);
                    setResult(Activity.RESULT_OK, intent);
                    ToastUtils.showCenterToast("作业发布成功");
                    finish();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<PublishHomeworkResurtInfo>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }

    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/images/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> news = PictureSelector.obtainMultipleResult(data);
                    List<String> newsPath = new ArrayList<>();
                    for (LocalMedia media : selectList) {
                        newsPath.add(media.getPath());
                    }
                    for (LocalMedia local : news) {
                        if (newsPath.contains(local.getPath())) {
                            continue;
                        } else {
                            selectList.add(local);
                        }
                    }
                    if (selectList.size() > 8) {
                        selectList = selectList.subList(0, 8);//有个加号占位符
                        ToastUtils.showCenterToast("最多上传" + maxSelectNum + "张图片");
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (et_content.getText().toString().trim().length() == 0 &&
                mRecorder == null &&
                selectList.size() == 0) {
            super.onBackPressed();
        } else {
            ExitDialog.getExitDialog("是否放弃此次编辑？").setExitListener(new ExitDialog.ExitListener() {
                @Override
                public void onExit(boolean exitState) {
                    if (exitState) {
                        PublishHomeworkActivity.super.onBackPressed();
                    }
                }
            }).show(getSupportFragmentManager(), "dialog");
        }
    }

    /**
     * 根据生命周期 管理播放录音
     */
    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }

    final int RESULT_CODE_STARTAUDIO = 10000;

    private void getAudioPermission() {
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.
                checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
        } else {
            //提示用户开户权限音频
            String[] perms = {"android.permission.RECORD_AUDIO"};
            ActivityCompat.requestPermissions(this, perms, RESULT_CODE_STARTAUDIO);
        }
    }

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
        switch (permsRequestCode) {
            case RESULT_CODE_STARTAUDIO:
                boolean albumAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (!albumAccepted) {
                    ToastUtils.showCenterToast("请开启应用录音权限");
                }
                break;
        }
    }


    @Override
    public void onItemClick(int position, View v) {
        if (selectList.size() > 0) {
            LocalMedia media = selectList.get(position);
            String pictureType = media.getPictureType();
            int mediaType = PictureMimeType.pictureToVideo(pictureType);
            switch (mediaType) {
                case 1:
                    PictureSelector.create(PublishHomeworkActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                    break;
/*                        case 2:
                            // 预览视频
                            PictureSelector.create(MainActivity.this).externalPictureVideo(media.getPath());
                            break;*/
                case 3:
                    // 预览音频
                    PictureSelector.create(PublishHomeworkActivity.this).externalPictureAudio(media.getPath());
                    break;
            }
        }
    }


    @Override
    public void onFinish(float seconds, String filePath) {
        mRecorder = new Recorder(seconds, filePath);
        int sec = (int) seconds;
        int width = sec * 50 + 200;
        width = width > 500 ? 500 : width;
        mAudio.setWidth(width);
        mAudio.setText(sec + "秒");
        mRelaAudio.setVisibility(View.VISIBLE);
    }
}
